/**
 * Created by dukes on 2015/11/12.
 */
class BattleScene extends eui.Component{
    private frameitem:FrameItem;
    private isOver:boolean;
    public constructor(){
        super();
        this.skinName = "pet.BattleSceneSkin";
        this.name = "battlescene";
        this.init();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.addedToStage, this );
        this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.removedFromStage, this);
    }
    private init(){
        this.frameitem = new FrameItem();
        this.frameitem.callObj = this;
        this.frameitem.callFun = this.update;
        this.tempQueue = [];
        this.usingQueue = [];
    }
    private interval;
    private warme;
    private warother;
    private speed:number;
    private hardness;
    private m_hurt;//my hurt
    private e_hurt;//enemy hurt
    private myBlood:number;
    private myMaxBlood:number;
    private enemyBlood:number;
    private enemyMaxBlood:number;
    private robHair:number;
    private curPet;
    private sourceType;
    private ready = false;
    private passed:number = 0;
    private phase = 0;
    /**
     * warother others' pet war data
     * petother others' pet data
     * robHair hair can rob
     * sourceType from where 0 : DateScene 1 : Revenge in mail
     * **/
    public setBattleData(warother,petother,robHair,sourceType,beHarm,harm){//fixme if this.parent == null not start
        this.ready = true;
        this.phase = 0;
        this.sourceType = sourceType;
        this.isOver = false;
        this.curPet = petother;
        var pet:Pet = Model.getPetById(PetMgr.getInstance().curIndatePetId);
        this.warme =  Model.GetPerAttrs(PetMgr.getInstance().curIndatePetId);
        this.warother = warother;
        this.speed = 200+(warother.speed-1)*30;
        this.hardness = warother.difficulty;
        this.robHair =  robHair;//(petother.hair + robHair.hair)*0.25;

        this.myBlood = this.myMaxBlood = this.warme.blood;
        this.enemyBlood = this.enemyMaxBlood = this.warother.blood;
        if( Model.me.platform != PlatformEnum.QQBROWSER){
            if( petother.userFigureurl &&  petother.userFigureurl != ""){
                this.img_head_1.source = petother.userFigureurl;
            }else{
                this.img_head_1.source = RES.getRes("default_head_"+(petother.userId%5));
            }
        }else{
            this.img_head_1.source = RES.getRes("default_head_"+(petother.userId%5));
        }


        this.m_hurt = harm;
        this.e_hurt = beHarm;
        this.img_money.source = pet.type == Model.GOOD_TYPE_CAT ? "img_money_cat" : "img_money_dog";
        this.lab_my_name.text = LimitStringLen(pet.userName);
        this.lab_the_name.text = LimitStringLen(petother.userName);
        this.pet_0.source= GameConst.Res_Root+"resource/assets/petpreview/"+pet.petId+".png";
        this.pet_1.source= GameConst.Res_Root+"resource/assets/petpreview/"+this.curPet.petId+".png";
        this.img_ready.source = "ready";
        this.img_ready.visible = true;
        this.passed = 0;
        this.img_ready.scaleX = this.img_ready.scaleY = 0.5;
        this.lab_my_gender.source = pet.sex == 0 ? "img_gender_male":"img_gender_female";
        this.lab_my_name_p.text = LimitStringLen(pet.name);
        this.lab_the_gender.source = petother.sex == 0 ? "img_gender_male":"img_gender_female";
        this.lab_the_name_p.text = LimitStringLen(petother.name);
        this.updateHp();
    }
    public start(){
        FrameMgr.getInstance().addControll(this.frameitem);
    }
    private reallyStart(){
        this.applyTempQueue();
        this.curTarget = this.usingQueue[0];
    }
    private lastQueueGap = 0;
    private applyTempQueue(){
        if( this.tempQueue.length==0){
            this.generateChess();
        }
        var lastGap = this.lastQueueGap;
        var chess:Chess;
        while( this.tempQueue.length > 0){
            var type = this.tempQueue.pop();
            if( type != -1){
                this.lastQueueGap = 0;
                chess = this.produceChess();
                chess.setType(type);
                chess.x = -144*(3-this.tempQueue.length+lastGap);
                this.usingQueue.push(chess);
            }else{
                this.lastQueueGap++;
            }
        }
    }
    private maxGeneratCnt = 45;
    private generatedCnt:number = 0;
    private tempQueue:number[];
    private usingQueue:Chess[];
    /**
     * every time 3 chesses
     * max generate 90 chesses
     * **/
    private generateChess(){
        if( this.generatedCnt >= this.maxGeneratCnt){
            return;
        }
        this.tempQueue=[-1,-1,-1];
        if( this.hardness == 1){
            var genCnt:number = Math.ceil(Math.random()*2);
        }else if( this.hardness == 2){
            genCnt = 2;
        }else{
            genCnt = 1 + Math.ceil(Math.random()*2);
        }
        //var genCnt:number = Math.ceil(Math.random()*this.hardness);
        //if(this.generatedCnt + genCnt > this.maxGeneratCnt){
        //    genCnt = this.maxGeneratCnt - this.generatedCnt;
        //}
        if( genCnt == 1){
            this.tempQueue[Math.floor(Math.random()*3)] = Math.floor(Math.random()*3);
        }else if(genCnt == 2){
            var hehe = Math.floor(Math.random()*3);
            this.tempQueue[hehe] = Math.floor(Math.random()*3);
            this.tempQueue[this.getIndexExcept(hehe)] = Math.floor(Math.random()*3);
        }else{
            var len = 3;
            while(len > 0){
                this.tempQueue[3-len]=Math.floor(Math.random()*3);
                len--
            }
        }

        this.generatedCnt += genCnt;
    }

    private getIndexExcept(idx):number{
        var hehe;
        while(true){
            hehe = Math.floor(Math.random()*3);
            if( hehe != idx ){
                return hehe;
            }
        }
    }
    private curTarget:Chess;
    private update(delta:number){
        if( this.isOver) return;
        var gap = this.speed * delta/1000;
        if( this.ready){
            this.passed+=delta;
            if(this.passed < 1000 && this.passed + delta >= 1000){
                this.img_ready.source = "go";
                this.img_ready.scaleX = this.img_ready.scaleY = 0.5;
            }else if( this.passed >= 2000){
                this.ready = false;
                this.img_ready.visible = false;
                this.reallyStart();
            }else{
                this.img_ready.scaleX = this.img_ready.scaleY = this.passed%1000/1000;
            }
            return;
        }
        var len = this.usingQueue.length;
        var chess:Chess;
        var needUpdateTarget = false;
        var minX:number = 480;
        for(var i = len - 1; i >= 0; i--){
            chess = this.usingQueue[i];
            chess.x+=gap;
            if( !chess.parent && chess.x >= -80){
                this.chess_group.addChild(chess);
            }else if( chess.x > 430 && this.curTarget == chess && !this.curTarget.checked){
                this.playEffect(BattleScene.MISS);
                this.curTarget.checked = true;
                needUpdateTarget = true;
                this.myBlood -= this.e_hurt;
                this.playHurt(this.e_hurt,true);
                if( this.myBlood <= 0){
                    this.myBlood = 0;
                    this.endType = 2;
                    this.isOver = true;
                    window["__pillageFinish"](0);
                }
                this.updateHp(1);
            }else if( chess.x > 480){
                this.chess_group.removeChild(chess);
                this.reclaimChess(chess);
                chess.reset();
            }
            minX = minX < chess.x ? minX : chess.x;
        }

        if( minX > -5){
            this.applyTempQueue();
        }
        if( needUpdateTarget){
            this.updateTarget();
        }
        if( len == 0 ){
            this.endType = 1;
            this.isOver = true;
            var per = Math.round(100*(1-this.enemyBlood/this.enemyMaxBlood));
            window["__pillageFinish"](per);
        }
        if(this.effectFlag){
            this.effect_asset.y -= delta/8;
            if(this.effect_asset.y < this.effectTarget){
                this.effectFlag = false;
                this.effect_asset.visible = false;
            }
        }
        if(this.hurt1flag){
            this.hurt_1.y -= delta/8;
            if(this.hurt_1.y < this.hurt1Target){
                this.hurt1flag = false;
                this.hurt_1.visible = false;
            }
        }
        if(this.hurt0flag){
            this.hurt_0.y -= delta/8;
            if(this.hurt_0.y < this.hurt0Target){
                this.hurt0flag = false;
                this.hurt_0.visible = false;
            }
        }
    }
    private updateTarget(){
        var len = this.usingQueue.length;
        var chess:Chess;
        this.curTarget = null;
        var hehe = false;
        for(var i = 0; i < len; i++){
            chess = this.usingQueue[i];
            if(hehe){
                this.curTarget = chess;
                break;
            }else if( chess.checked ){
                hehe = true;
            }
        }
        if( this.curTarget == null){
            this.curTarget = this.usingQueue[0];
        }
    }
    private endType:number;
    private check(value){
        if( this.isOver) return;
        if( this.curTarget == null || this.curTarget.x < 350 ) return;//not in check scope

        var checkValue = this.checkValue(value,this.curTarget.type);
        if( checkValue == 0){
            this.playEffect(BattleScene.AOH);
        }else if( checkValue == 1){
            if( this.curTarget.x >= 350 && this.curTarget.x <= 385){//perfect
                this.playEffect(BattleScene.PERFECT);
                this.enemyBlood -= this.m_hurt;
                this.playHurt(this.m_hurt,false);
                if( this.enemyBlood <= 0){
                    this.enemyBlood = 0;
                    this.endType = 0;
                    this.isOver = true;
                    window["__pillageFinish"](100);
                }
                this.updateHp(2);
            }else if( this.curTarget.x > 385 && this.curTarget.x <= 430){//good
                this.playEffect(BattleScene.GOOD);
                this.enemyBlood -= Math.round(this.m_hurt * 0.75);
                this.playHurt(Math.round(this.m_hurt* 0.75),false);
                if( this.enemyBlood <= 0){
                    this.enemyBlood = 0;
                    this.endType = 0;
                    this.isOver = true;
                    window["__pillageFinish"](100);
                }
                this.updateHp(2);
            }
            //this.chess_group.removeChild(this.curTarget);
            //this.reclaimChess(this.curTarget);
        }else if( checkValue == -1){
            this.playEffect(BattleScene.BAD);
            this.myBlood -= this.e_hurt;
            this.playHurt(this.e_hurt,true);
            if( this.myBlood <= 0){
                this.myBlood = 0;
                this.endType = 2;
                this.isOver = true;
                window["__pillageFinish"](0);
            }
            this.updateHp(1);
        }
        if( checkValue != -2 && this.curTarget && this.curTarget.parent){
            this.chess_group.removeChild(this.curTarget);
            this.reclaimChess(this.curTarget);
        }

        this.updateTarget();
    }
    /**
     * 0 击败对方
     * 1 时间结束
     * 2 自己被打败
     * */
    public showResult(hairs){
        FrameMgr.getInstance().delController(this.name);
        this.isOver = true;
        if( hairs != 0){
            DiamondElement.getInstance().updateDisplay();
        }
        if( this.endType == 0){
            RemindPanel.getInstance().showContent("敌休！\n在您的英明领导下，本次共抢到"+hairs+"毛发！哼，还有谁！",this, this.onReturn, this.onReturn);
        }else if( this.endType == 1){
            if( hairs != 0) {
                RemindPanel.getInstance().showContent("斯狗矣！\n本次作战共抢到"+hairs+"毛，实在是可喜可贺呀！",this, this.onReturn, this.onReturn);
            }else{
                RemindPanel.getInstance().showContent("残念！\n什么都没抢到！一定是今天的草皮太滑了！",this, this.onReturn, this.onReturn);
            }
        }else if( this.endType == 2){
            RemindPanel.getInstance().showContent("残念！\n什么都没抢到！一定是今天的草皮太滑了！",this, this.onReturn, this.onReturn);
        }else if( this.endType == 3){
            ShowHint("战斗失败");
        }
        Model.checkGuide("robbed");
    }
    private checkValue(type0, type1):number{
        var gap = type0 - type1;
        if(gap == 0){//equal
            return 0;
        }else if( gap == 1 || gap == -2 ){//lager than
            return 1;
        }else{//less than
            return -1;
        }
        return -2;
    }
    //0 all 1 mine 2 others
    private gain;
    private updateHp(type=0){
        if( type == 1 || type == 0){
            this.group_hp_0.text = this.myBlood+"p"+this.myMaxBlood;
            //GetUIAssetsNum(this.myBlood+"/"+this.myMaxBlood,this.group_hp_0);
            this.pro_0.width = 118*this.myBlood/this.myMaxBlood;
        }
        if( type == 2 || type == 0){
            this.group_hp_1.text = this.enemyBlood+"p"+this.enemyMaxBlood;
            //GetUIAssetsNum(this.enemyBlood+"/"+this.enemyMaxBlood,this.group_hp_1);
            this.pro_1.width = 118*this.enemyBlood/this.enemyMaxBlood;
        }
        var per = Math.round(100 * (1 - this.enemyBlood / this.enemyMaxBlood));
        var gain = per >= 50 ? Math.round(this.robHair*per/100) : 0;
        if( this.gain != gain){
            this.gain = gain;
            this.group_money.text =GetNumString(gain,false,true);
            //GetUIAssetsNum(gain, this.group_money,1.0,false,false,null,"preload_json.num_",true);
        }
    }
    private static PERFECT:string = "battle_perfect";
    private static GOOD:string = "battle_good";
    private static BAD:string = "battle_bad";
    private static MISS:string = "battle_miss";
    private static AOH:string = "battle_aoh";
    private effectFlag:boolean = false;
    private effectTarget:number;
    private playEffect(hehe:string){
        this.effect_asset.source = hehe;
        this.effect_asset.visible = true;
        this.effect_asset.y = 537;
        this.effectTarget = 455;
        this.effectFlag = true;
    }
    private hurt0flag:boolean = false;T
    private hurt0Target:number = 350;
    private hurt1flag:boolean = false;
    private hurt1Target:number = 230;
    private playHurt(num, isMe){
        return;
        this.hurt1flag = this.hurt_1.visible = !isMe;
        this.hurt0flag = this.hurt_0.visible = isMe;
        //SoundMgr.getInstance().playEffect(SoundMgr.HIT);
        if( isMe){
            this.hurt_0.y = 409;
            this.hurt_0.text = "-"+num;
            //GetUIAssetsNum("-"+num,this.hurt_0,1.0,true,false,null,'battle_reduce_');
            ShakeMgr.instance().addShakeItem(this.pet_0.name,{gap:3,cnt:4,dis:this.pet_0,ox:5,type:"shakeh"});
            EffectMgr.getInstance().playEffect("claw1");
        }else{
            this.hurt_1.y = 289;
            this.hurt_1.text = "-"+num;
            //GetUIAssetsNum("-"+num,this.hurt_1,1.0,true,false,null,'battle_reduce_');
            ShakeMgr.instance().addShakeItem(this.pet_1.name,{gap:3,cnt:4,dis:this.pet_1,ox:373,type:"shakeh"});
            EffectMgr.getInstance().playEffect("claw2");
        }
    }

    public reset(){
        FrameMgr.getInstance().delController(this.name);
        var chess:Chess;
        while(this.usingQueue.length){
            chess = this.usingQueue.pop();
            this.reclaimChess(chess);
        }
        var element;
        while(this.chess_group.numElements){
            element = this.chess_group.removeChildAt(0);
            if( element instanceof Chess){
                this.reclaimChess(element);
            }
        }
        this.curPet = null;
        this.curTarget = null;
        this.warme = null;
        this.warother = null;
        this.effect_asset.visible = this.hurt_0.visible = this.hurt_1.visible = false;
        this.effectFlag = this.hurt0flag = this.hurt1flag = false;
        this.generatedCnt = 0;
        this.img_ready.visible = false;
    }
    public onJiandao(evt:egret.TouchEvent){
        this.check(0);
    }
    public onShitou(evt:egret.TouchEvent){
        this.check(1);
    }
    public onBu(evt:egret.TouchEvent){
        this.check(2);
    }
    public onReturn(evt:egret.TouchEvent){
        if( Model.GuideType && Model.GuideType != "rob_complete") return;
        if( !this.isOver){
            this.endType = 3;
            this.isOver = true;
            window["__pillageFinish"](0);

        }
        Model.checkGuide("rob_complete");
        if( this.sourceType == 0){
            SceneMgr.getInstance().switchScene(SceneMgr.SCENE_GETOUT);
        }else{
            SceneMgr.getInstance().switchScene(SceneMgr.SCENE_MAIL);
        }
    }
    private addedToStage(evt:egret.Event){
        this.stone_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onShitou,this);
        this.jiandao_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onJiandao, this);
        this.bu_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBu,this);
        this.img_return.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onReturn, this);
        SoundMgr.getInstance().playBattleBg();
    }
    private removedFromStage(evt:egret.Event){
        this.stone_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onShitou,this);
        this.jiandao_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onJiandao, this);
        this.bu_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onBu,this);
        this.img_return.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onReturn, this);
        if( this.interval){
            clearInterval(this.interval);
        }
        this.reset();
    }
    private stone_btn:eui.Button;
    private jiandao_btn:eui.Button;
    private bu_btn:eui.Button;
    private img_head_0:eui.Image;
    private img_head_1:eui.Image;
    private img_money:eui.Image;
    private img_return:eui.Image;
    private pro_0:eui.Image;
    private pro_1:eui.Image;
    private pet_0:eui.Image;
    private pet_1:eui.Image;
    private effect_asset:eui.Image;
    private img_ready:eui.Image;
    private lab_my_name:eui.Label;
    private lab_the_name:eui.Label;
    private group_hp_0:eui.BitmapLabel;
    private group_hp_1:eui.BitmapLabel;
    private group_money:eui.BitmapLabel;
    private chess_group:eui.Group;
    private hurt_0:eui.BitmapLabel;
    private hurt_1:eui.BitmapLabel;
    private lab_my_name_p:eui.Label;
    private lab_the_name_p:eui.Label;
    private lab_my_gender:eui.Image;
    private lab_the_gender:eui.Image;
    public partAdded(name:string, instance:any){
        super.partAdded(name, instance);
        if(name == "stone_btn"){
            this.stone_btn = instance;
        }else if( name == "jiandao_btn"){
            this.jiandao_btn = instance;
        }else if( name == "bu_btn"){
            this.bu_btn = instance;
        }else if( name == "img_head_0"){
            this.img_head_0 = instance;
            if( Model.me.platform != PlatformEnum.QQBROWSER){
                this.img_head_0.source = Model.me.figureurl;
            }else{
                this.img_head_0.source = RES.getRes("default_head_"+(Model.me.id%5));
            }
        }else if( name == "img_head_1"){
            this.img_head_1 = instance;
        }else if( name == "img_money"){
            this.img_money = instance;
        }else if( name == "img_return"){
            this.img_return = instance;
        }else if( name == "pro_0"){
            this.pro_0 = instance;
        }else if( name == "pro_1"){
            this.pro_1 = instance;
        }else if( name == "lab_my_name"){
            this.lab_my_name = instance;
        }else if( name == "lab_the_name"){
            this.lab_the_name = instance;
        }else if( name == "group_hp_0"){
            this.group_hp_0 = instance;
            this.group_hp_0.textAlign = "center";
        }else if( name == "group_hp_1"){
            this.group_hp_1 = instance;
            this.group_hp_1.textAlign = "center";
        }else if( name == "group_money"){
            this.group_money = instance;
            this.group_money.textAlign = "center";
        }else if( name == "chess_group"){
            this.chess_group = instance;
        }else if( name == "pet_0"){
            this.pet_0 = instance;
        }else if( name == "pet_1"){
            this.pet_1 = instance;
        }else if( name == "effect_asset"){
            this.effect_asset = instance;
        }else if( name == "hurt_0"){
            this.hurt_0 = instance;
        }else if( name == "hurt_1"){
            this.hurt_1 = instance;
        }else if( name == "img_ready"){
            this.img_ready = instance;
            AnchorUtil.setAnchor(this.img_ready,0.5,0.5);
        }else if( name == "lab_my_gender"){
            this.lab_my_gender = instance;
        }else if( name == "lab_my_name_p"){
            this.lab_my_name_p = instance;
        }else if( name == "lab_the_name_p"){
            this.lab_the_name_p = instance;
        }else if( name == "lab_the_gender"){
            this.lab_the_gender = instance;
        }
    }
    private _chessCache:Chess[] = [];
    private _getCnt:number = 0;
    private produceChess():Chess{
        this._getCnt++;
        //console.log(this._getCnt);
        var result:Chess;
        if( this._chessCache.length)
            result = this._chessCache.pop();
        result =  new Chess();
        result.name = "chess"+this._getCnt;
        return result;
    }
    private reclaimChess(chess:Chess){
        var idx = this.usingQueue.indexOf(chess);
        if( idx != -1){
            this.usingQueue.splice(idx,1);
            //if( this.usingQueue.length == 0 && this.generatedCnt >= this.maxGeneratCnt){
            //    FrameMgr.getInstance().delController(this.name);
            //}
        }
        if( this._chessCache.indexOf(chess) == -1)
            this._chessCache.push(chess);
    }
    private static _instance:BattleScene;
    public static getInstance():BattleScene{
        if( BattleScene._instance == null)
            BattleScene._instance = new BattleScene();
        return BattleScene._instance;
    }
}

class Chess extends eui.Image{
    public type:number = -1;
    public checked:boolean = false;
    public static CHESS_ENUM:number = 0;
    public constructor(){
        super();
        Chess.CHESS_ENUM++;
        //console.log("chess cnt : ", Chess.CHESS_ENUM);
    }
    //1 剪刀 2石头 3布
    public setType(type){
        this.type = type;
        if( this.type == 0){
            this.source = "battle_jiandao";
        }else if( this.type == 1){
            this.source = "battle_shitou";
        }else if( this.type == 2){
            this.source = "battle_bu";
        }
    }

    public reset(){
        this.checked = false;
    }
}